/*
 * Copyright 2007-2009 Taglab Limited.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.taglab.chic.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StopWatch;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;


/**
 * Simple filter that will deligate to a resource in the webapp if it exists
 * otherwise will dispatch the request to the named servlet. Used for mounting
 * controllers over a particular domain as well as having static resources under
 * same directory.
 *
 * XXX move caching, and profiling out of filter
 *
 * @author Markus Kobler
 */
public class DispatcherFilter extends GenericFilterBean {

  private final static Logger logger = LoggerFactory.getLogger(DispatcherFilter.class);

  private final static String DEFAULT_SERVLET_DELEGATE_CLASS = "org.springframework.web.servlet.DispatcherServlet";

  private String delegateClass = DEFAULT_SERVLET_DELEGATE_CLASS;

  private HttpServlet delegate;

  private boolean addCachingHeaders = false;
  private long cacheMaxAge = 60 * 60 * 24 * 7; // default to a week
  private String excludes;

  public void setDelegateClass(String delegateClass) {
    this.delegateClass = delegateClass;
  }

  public void setAddCachingHeaders(boolean addCachingHeaders) {
    this.addCachingHeaders = addCachingHeaders;
  }

  public void setCacheMaxAge(long cacheMaxAge) {
    this.cacheMaxAge = cacheMaxAge;
  }

  public void setExcludes(String excludes) {
    this.excludes = excludes;
  }

  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
    throws IOException, ServletException {

    StopWatch watch = null;
    if (logger.isDebugEnabled()) {
      watch = new StopWatch();
      watch.start();
    }

    String resourcePath = parseResourcePath((HttpServletRequest) request);

    if ( excludes != null && resourcePath.startsWith(excludes)) {

      logger.info("[{}] excluded '{}', applying filter chain", resourcePath, excludes);

      filterChain.doFilter(request, response);      

    } else if(testForWebappResource(resourcePath)) {

      logger.debug("[{}] found and is a file", resourcePath);

      if( addCachingHeaders ) {
        long expires = System.currentTimeMillis() + cacheMaxAge * 1000;
        
        logger.debug("adding 'Cache-Control: max-age={} and Expires: {}", cacheMaxAge, expires);
        
        ((HttpServletResponse)response).addHeader("Cache-Control", "max-age="+ cacheMaxAge);
        ((HttpServletResponse)response).addDateHeader("Expires", expires);
      }

      filterChain.doFilter(request, response);

    } else {

      logger.debug("[{}] not found, forwarding to DispatcherServlet", resourcePath);

      delegate.service(request, response);

    }

    if (watch != null) {
      watch.stop();
      logger.debug("[{}] took {}ms", ((HttpServletRequest) request).getRequestURI(), watch.getTotalTimeMillis());
    }

  }

  protected void initFilterBean() throws ServletException {
    
    try {
      delegate = (HttpServlet) Class.forName(delegateClass).newInstance();
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }

    delegate.init(new ServletConfig() {

      public String getServletName() {
        return getFilterConfig().getFilterName();
      }

      public ServletContext getServletContext() {
        return getFilterConfig().getServletContext();
      }

      public String getInitParameter(String name) {
        return getFilterConfig().getInitParameter(name);
      }

      public Enumeration getInitParameterNames() {
        return getFilterConfig().getInitParameterNames();
      }
    });

  }


  public void destroy() {
    if (delegate != null) {
      delegate.destroy();
      delegate = null;
    }
  }


  private String parseResourcePath(HttpServletRequest request) {

    String path = request.getRequestURI();

    int contextPathLength = request.getContextPath().length();
    if (contextPathLength > 0) {
      path = path.substring(contextPathLength);
    }

    int semiColon = path.indexOf(';');
    if (semiColon > 0) {
      path = path.substring(0, semiColon);
    }

    return path;
  }


  private boolean testForWebappResource(String path) throws IOException, ServletException {

    if (path == null || !path.startsWith("/"))
      throw new IllegalArgumentException("Path must start with a / [" + path + "]");

    String realPath = getServletContext().getRealPath(path);

    if (realPath != null) {
      return new File(realPath).isFile();
    }

    return getServletContext().getResource(path) != null;
  }

}